import React, { useState } from 'react';
import Dropdown from '@knownsec/react-component/dist/Dropdown';
import Confirm from '@knownsec/react-component/dist/Confirm';
import Form from '@knownsec/react-component/dist/Form';
import Message from '@knownsec/react-component/dist/Message';
import Tabs from '@knownsec/react-component/dist/Tabs';
import s from './style.module.css';
import Notification from '../Notification';
import fetchFer from 'API/fetch';
import cn from 'classnames';
import { Link } from 'react-router-dom'
import cookie from 'react-cookies'
import { datetime } from '../../../common/formatter';
import packageJson from '../../../../package.json'
const { TabPane } = Tabs

export default function ({ history }) {
  const layout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 18 },
  };
	const logo = window?.kuiper?.app?.config['@kuiper/react-base']?.logo?.icon
	const { casUrl, consoleLink } = window?.kuiper?.app?.config[packageJson?.name];
	const [notificationGrouped, setNotificationGrouped] = useState({
		告警通知: { count: 0, data: [] },
		漏洞速递: { count: 0, data: [] },
		服务公告: { count: 0, data: [] },
	});
	const [count, setCount] = useState({
		告警通知: 0,
		漏洞速递: 0,
		服务公告: 0,
	});
  const [showArrow, setArrow] = useState(false);
  const [unReadTotal, setUnRead] = useState(0);
  const [visible, setVisible] = useState(false);
	const [plan, setPlan] = React.useState([]);
  const [form] = Form.useForm();
  const [name, setName] = useState('')
	async function getPlanData(taskType) {
		const res = await fetchFer(`/api/v2/index/get_plan`, {
			method: 'GET',
		}).catch(e => {
			return {};
		});
		if (res.msg === 'ok') {
			setPlan(res.results);
			sessionStorage.setItem('planTimeOut', res.results.expire_time);
		}
	}
	async function getUserData() {
		const res = await fetchFer(`/api/v2/users/user_info`, {
			method: 'GET',
		}).catch(e => {
			return {};
		});
		if (res.msg === 'ok') {
			setName(res.results.username);
		}
	}
  const logoutMethod = () => {
    Confirm({
      className: [s.normal],
      pro: true,
      title: '提示',
      message: <div className="confirmbox">确认要退出吗？</div>,
      onconfirm: () => {
				window.location.href = '/api/v2/users/logout?service=' + window.location.origin + '/'
      },
      oncancel: () => {},
    });
  };
  const pushMsg = () => {
    history.push('/message');
  };
	const notificationCentre = (
		<div className={cn('p16', 'bsbb', s.notificationBox)}>
			<div className='df jcsb aic'>
				<span className='white-color'>站内消息</span>
				<Link to="">
					<span className='main-color'>{'更多>'}</span>
				</Link>
			</div>
			{/* 从左至右默认选择第一个有数据的tab页 */}
			<Tabs>
				{Object.entries(notificationGrouped).map(([type, info]) => {
					const isShow = count[type] > 0 ? 'inline' : 'none';
					return (
						<TabPane
							key={type}
							tab={
								<span className={s.tabName}>
									{type}
									{type === '告警通知' && (
										<span
											className={s.count}
											style={{ display: isShow }}
										>
											{count[type] > 99 ? '99+' : count[type]}
										</span>
									)}
								</span>
							}
						>
							{/* <NotificationList
								notificationList={info}
								onChange={getData}
								type={type}
							/> */}
						</TabPane>
					);
				})}
			</Tabs>
		</div>
	)
  const msgMenu = (
		<div className={s.user}>
			<table border="0" cellPadding="0" cellSpacing="0">
				{function () {
					let cookieArr = document.cookie.split(';').map(e => {
						return e.trim();
					});
					const list = cookieArr.includes('from=https://sso.365cyd.com') ? <></> : <>
							<tr>
								<td className={cn('cp', s.link_a)}>
									<a href={casUrl} rel="noreferrer" target="_blank">
										创宇通行证
									</a>
								</td>
							</tr>
							{consoleLink && (
								<tr>
									<td className={cn('cp', s.link_a)}>
										<a href={consoleLink} rel="noreferrer" target="_blank">
											云防御控制台
										</a>
									</td>
								</tr>
							)}
						</>
					return list
				}()}
				<tr>
					<td className={cn('cp', s.link_a)}>
						<Link to={'/disclaimer'}>
							服务条款
						</Link>
					</td>
				</tr>
				<tr>
					<td className={cn('cp', s.link_a)} href="javascript:;" onClick={logoutMethod}>安全退出</td>
				</tr>
			</table>
		</div>
  );
  const planMenu = (
    <div className={s.plan}>
			<table border="0" cellPadding="0" cellSpacing="0">
				<tr className={s.tr1}>
					<td className={s.versionLabel}>套餐版本</td>
					<td className={cn(s.tdInfo, s.version)}>{plan.version || '未开通'}</td>
				</tr>
				<tr className={s.tr2}>
					<td>Web资产数</td>
					<td className={s.tdInfo}>
						{plan.jobs_count >= 0 ? plan.jobs_count : '--'}个
					</td>
				</tr>
				{/* <tr>
					<td>监测次数</td>
					<td>{plan.monitor_count}</td>
				</tr> */}
				{plan.host_job_count > 0 && (
					<tr className={s.tr3}>
						<td>主机资产数</td>
						<td className={s.tdInfo}>
							{plan.host_job_count >= 0 ? plan.host_job_count : '--'}个
						</td>
					</tr>
				)}
				<tr className={s.tr3}>
					<td>到期时间</td>
					<td className={s.tdInfo}>
						{datetime(plan.expire_time, 'YYYY-MM-DD') || '--'}
					</td>
				</tr>
			</table>
		</div>
  );
  const onValues2 = (data) => {
    let values = recursionForm(data);
    const rule = /^\+?[1-9][0-9]*$/;
    if (values.hasOwnProperty('access_token_limit') && !rule.test(values.access_token_limit)) {
      form.current.setFieldsValue({ access_token_limit: '' });
    } else {
      form.current.setFieldsValue(values);
    }
  };
  const submitInfo = () => {
    form.current.validateFields().then(async (data) => {
      const res = await putTokenTime(data);
      setVisible(false);
      form.current.resetFields();
      if (res.status === 'success') {
        Message.show({
          pro: true,
          type: 'success',
          message: '操作成功',
          showClose: false,
        });
      }else{
        Message.show({
          pro: true,
          type: 'error',
          message: `操作失败`,
          showClose: false,
        });
      }
    });
  };
  const getData = () => {
    getMailList({ status: 0 }).then((res) => {
      if (res.status === 'success') {
        const t = res?.data?.total || 0;
        setUnRead(t);
      }
    });
  };
  React.useEffect(() => {
		getPlanData()
		getUserData()
    // getData();
    // const seT = setInterval(() => {
    //     if (name !== cookie.load('username')) {
    //         window.location.reload() //  更新时判断用户是否变更，如果变更刷新页面重新加载菜单栏
    //         return false
    //     }
    //   getData();
    // }, 60 * 1000);
    // return () => {
    //   clearInterval(seT);
    // };
  }, []);
  return (
    <div className={s.headerBox}>
      <div className={s.Headerleft}>
				{logo && <img className={s.logo} src={logo} />}
      </div>
      <div className={s.Headerright}>
				<Link to={'/'} className={s.HeaderLink}>安全概览</Link>
				<Notification className={s.dropdowns} casUrl={casUrl} />
        <Dropdown
					arrow={false}
					overlay={planMenu}
					placement="bottom"
					className='ml16'
				>
					<span className={s.dropdowns} onClick={(e) => e.preventDefault()}>
						<span
							className={s.icon}
							style={{ display: plan.warning_icon ? 'block' : 'none' }}
						>
							已过期
						</span>
						<span className={cn('pr', s.t1)}>套餐</span>
					</span>
				</Dropdown>
				<Dropdown
					arrow={false}
					overlay={msgMenu}
					placement="bottomRight"
					onVisibleChange={(e) => setArrow(e)}
				>
					<span className={cn(s.dropdowns, s.bl, 'pl20')} onClick={(e) => e.preventDefault()}>
						<span>{name}</span>
						<span
							className={s.rightIcon}
							style={{ transform: showArrow ? 'rotate(45deg)' : 'rotate(-135deg)' }}
						></span>
					</span>
				</Dropdown>
      </div>
    </div>
  );
}
